package leetcode.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 最后执行的输入： [4,-7,-3,null,null,-9,-3,9,-7,-4,null,6,null,-6,-6,null,null,0,6,5,null,9,null,null,-1,-4,null,null,null,-2]
 *
 * @author wangmaolin1
 * @date 2021/12/26 下午6:50
 */
public class _104二叉树最大深度 {

    /*
                4
         -7             -3
                  -9           -3
           -7          -4            6
              -6     -6                 0
           6     5      9
         -1  -4            -2
      */
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(len(root.left), len(root.right)) + 1;
    }

    public int maxDepthBFS(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int heightn = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            heightn++;

        }
        return heightn;
    }

    private int len(TreeNode node) {
        if (node == null) {
            return 0;
        }
        return Math.max(len(node.left), len(node.right)) + 1;
    }

}
